<template>
  <div>
    <!-- 查询栏 -->
    <div class="toolbar">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            style="width: 100%" />
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
            style="width: 100%" />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchPlate"
            placeholder="请输入车牌号"
            clearable
            style="width: 100%" />
        </el-col>
        <el-col :span="3">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
            style="width: 100%">
            查询
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-button
            @click="resetSearch"
            style="width: 100%">
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 操作区 -->
    <div class="button-bar">
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete">
        批量删除
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="openAddDialog">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="paginatedData"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="车辆ID" width="80" />
      <el-table-column prop="color" label="颜色" width="100" />
      <el-table-column prop="plateNumber" label="车牌号" width="140" />
      <el-table-column prop="ownerName" label="车主姓名" width="120" />
      <el-table-column prop="ownerPhone" label="联系电话" width="130" />
      <el-table-column label="车辆照片" width="100">
        <template #default="scope">
          <img
            :src="scope.row.photo"
            alt="车辆照片"
            style="width: 60px; height: 60px; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <i
            class="el-icon-edit"
            @click="openEditDialog(scope.row)"
            style="cursor:pointer; margin-right: 10px" />
          <i
            class="el-icon-delete"
            @click="confirmDelete(scope.row)"
            style="cursor:pointer" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="total, prev, pager, next, jumper"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="filteredData.length"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: center;" />

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%"
      @close="resetDeleteData">
      <span>确定要删除该车辆记录吗？</span>
      <template #footer>
        <el-button @click="resetDeleteData">取消</el-button>
        <el-button type="primary" @click="deleteConfirmed">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量删除弹窗 -->
    <el-dialog
      title="确认批量删除"
      :visible.sync="batchDeleteDialogVisible"
      width="30%"
      @close="resetBatchDeleteData">
      <span>确定要删除选中的车辆记录吗？</span>
      <template #footer>
        <el-button @click="resetBatchDeleteData">取消</el-button>
        <el-button type="primary" @click="batchDeleteConfirmed">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑车辆弹窗 -->
    <el-dialog
      :title="editForm.id ? '编辑车辆' : '添加车辆'"
      :visible.sync="editDialogVisible"
      width="600px">
      <el-form
        :model="editForm"
        label-width="100px"
        :rules="rules"
        ref="editFormRef"
        label-position="left">
        <el-form-item label="车辆ID" prop="id">
          <el-input v-model="editForm.id" :disabled="!!editForm.id" />
        </el-form-item>
        <el-form-item label="颜色" prop="color" required>
          <el-input v-model="editForm.color" autocomplete="off" />
        </el-form-item>
        <el-form-item label="车牌号" prop="plateNumber" required>
          <el-input v-model="editForm.plateNumber" autocomplete="off" />
        </el-form-item>
        <el-form-item label="车主姓名" prop="ownerName" required>
          <el-input v-model="editForm.ownerName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系电话" prop="ownerPhone" required>
          <el-input v-model="editForm.ownerPhone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="车辆照片" prop="photo">
          <el-input v-model="editForm.photo" placeholder="请输入照片URL" autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="editForm.remark" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 无数据提示 -->
    <div v-if="filteredData.length === 0 && !isLoading" class="no-data">
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      startDate: '',
      endDate: '',
      searchPlate: '',
      currentPage: 1,
      pageSize: 5,
      selection: [],
      deleteDialogVisible: false,
      batchDeleteDialogVisible: false,
      deleteRowData: null,
      editDialogVisible: false,
      editForm: {
        id: null,
        color: '',
        plateNumber: '',
        ownerName: '',
        ownerPhone: '',
        photo: '',
        remark: '',
        createTime: ''
      },
      isLoading: false,
      rules: {
        color: [{ required: true, message: '请输入颜色', trigger: 'blur' }],
        plateNumber: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
        ownerName: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
        ownerPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
      },
      originalData: [
        {
          id: 1,
          color: '白色',
          plateNumber: '浙A12345',
          ownerName: '张三',
          ownerPhone: '13800138000',
          photo: 'https://via.placeholder.com/60',
          remark: '常驻业主车辆',
          createTime: '2023-05-01 10:00:00'
        },
        {
          id: 2,
          color: '黑色',
          plateNumber: '浙B67890',
          ownerName: '李四',
          ownerPhone: '13800138001',
          photo: 'https://via.placeholder.com/60',
          remark: '临时车位',
          createTime: '2023-06-01 11:30:00'
        }
      ]
    };
  },
  computed: {
    filteredData() {
      return this.originalData.filter(item => {
        const plateMatch = !this.searchPlate || item.plateNumber.includes(this.searchPlate);
        const itemDate = new Date(item.createTime);
        const start = this.startDate ? new Date(this.startDate) : null;
        const end = this.endDate ? new Date(this.endDate) : null;
        const dateMatch = (!start || itemDate >= start) && (!end || itemDate <= end);
        return plateMatch && dateMatch;
      });
    },
    paginatedData() {
      return this.filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    handleSearch() {
      this.isLoading = true;
      setTimeout(() => {
        this.currentPage = 1;
        this.isLoading = false;
        if (!this.filteredData.length) {
          this.$message.info('没有找到匹配的数据');
        }
      }, 600);
    },
    resetSearch() {
      this.startDate = '';
      this.endDate = '';
      this.searchPlate = '';
      this.currentPage = 1;
    },
    confirmDelete(row) {
      this.deleteRowData = row;
      this.deleteDialogVisible = true;
    },
    resetDeleteData() {
      this.deleteRowData = null;
      this.deleteDialogVisible = false;
    },
    deleteConfirmed() {
      if (this.deleteRowData) {
        this.originalData = this.originalData.filter(item => item.id !== this.deleteRowData.id);
        this.resetDeleteData();
        this.$message.success('删除成功');
      }
    },
    handleBatchDelete() {
      if (!this.selection.length) {
        this.$message.warning('请至少选择一项');
        return;
      }
      this.batchDeleteDialogVisible = true;
    },
    batchDeleteConfirmed() {
      const selectedIds = this.selection.map(item => item.id);
      this.originalData = this.originalData.filter(item => !selectedIds.includes(item.id));
      this.selection = [];
      this.batchDeleteDialogVisible = false;
      this.$message.success('批量删除成功');
    },
    resetBatchDeleteData() {
      this.selection = [];
      this.batchDeleteDialogVisible = false;
    },
    openAddDialog() {
      this.resetEditForm();
      this.editDialogVisible = true;
    },
    openEditDialog(row) {
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    resetEditForm() {
      this.editForm = {
        id: null,
        color: '',
        plateNumber: '',
        ownerName: '',
        ownerPhone: '',
        photo: '',
        remark: '',
        createTime: ''
      };
    },
    saveEdit() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return;

        if (this.editForm.id) {
          const index = this.originalData.findIndex(item => item.id === this.editForm.id);
          if (index !== -1) {
            this.$set(this.originalData, index, { ...this.editForm });
          }
          this.$message.success('编辑成功');
        } else {
          const maxId = this.originalData.reduce((max, item) => (item.id > max ? item.id : max), 0);
          this.editForm.id = maxId + 1;
          this.editForm.createTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
          this.originalData.push({ ...this.editForm });
          this.$message.success('添加成功');
        }
        this.editDialogVisible = false;
      });
    }
  }
};
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
}
.button-bar {
  background-color: #f2f2f2;
  padding: 6px 10px;
  margin-bottom: 20px;
}
.el-button {
  margin-right: 10px;
}
.el-icon-edit,
.el-icon-delete {
  cursor: pointer;
  margin-right: 10px;
  color: #2a6496;
}
.el-table {
  border: 1px solid #dcdfe6;
  margin-top: 10px;
}
.el-table th {
  background-color: #f2f2f2;
  font-weight: bold;
}
.no-data {
  text-align: center;
  padding: 50px;
  color: #999;
}
</style>
